package com.hle;

public class BruteForce02 {
	public static int[] next(String pattern) {
		int len = pattern.length();
		int[] next = new int[len];
		int i = 0;
		int n = next[i] = -1;
		
		int imax = len - 1;
		
		while (i < imax) {
			if (n < 0 || pattern.charAt(i) == pattern.charAt(n)) {
				next[++i] = ++n;
			}else {
				n = next[n];
			}
		}
		return  next;
	}
	
	public static int indexOf(String text, String pattern) {
		if (text == null || pattern == null) return -1;
		int tlen = text.length();
		int plen = pattern.length();
		if (tlen == 0 || plen == 0 || plen > tlen) return -1;
		int tmax = tlen - plen;
		for (int ti = 0 ; ti <= tmax; ti++) {
			int pi = 0;
			for (; pi < plen; pi++) {
				if(text.charAt(ti + pi) != pattern.charAt(pi)) break;
			}
			if (pi == plen) return ti;
		}
		return -1;
	}
}
